<!DOCTYPE html>
<html lang="zh-cn" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>设置中心 - Dark Video</title>
    <link th:href="@{/assets/zui/css/zui.min.css}" rel="stylesheet">
    <link th:href="@{/assets/zui/lib/datagrid/zui.datagrid.min.css}" rel="stylesheet">
    <link th:href="@{/assets/css/common.css}" rel="stylesheet">
</head>
<body>

<nav th:replace="common/nav::html"></nav>

<div class="container-fluid">
    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="active"><a href="#res_tab" aria-controls="res_setting" role="tab" data-toggle="tab">资源设置</a></li>
        <li role="presentation"><a href="#carousel_tab" aria-controls="index_carousel" role="tab" data-toggle="tab">轮播图设置</a></li>
        <li role="presentation"><a href="#password_tab" aria-controls="password_carousel" role="tab" data-toggle="tab">密码设置</a></li>
        <li role="presentation"><a href="#content_tab" aria-controls="content_carousel" role="tab" data-toggle="tab">内容管理</a></li>
    </ul>
    <!-- Tab panes -->
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane fade in active" id="res_tab">
            <div class="panel panel-info">
                <div class="panel-body">
                    <div class="input-group">
                        <span class="input-group-addon">内容目录</span>
                        <input type="text" id="inputResContent" class="form-control">
                    </div><br>
                    <div class="input-group">
                        <span class="input-group-addon">缩略图目录</span>
                        <input type="text" id="inputResThumbnail" class="form-control">
                    </div><br>
                    <div class="input-group">
                        <span class="input-group-addon">内容服务器</span>
                        <input type="text" id="inputContentIp" class="form-control">
                    </div><br>
                    <div class="input-group">
                        <span class="input-group-addon">缩略图服务器</span>
                        <input type="text" id="inputThumbnailIp" class="form-control">
                    </div><br>
                    <button class="btn btn-primary" type="button" onclick="updateRes()">更新配置信息</button>
                    <button class="btn btn-warning disabled" id="contentIndexBtn" type="button" onclick="buildContentIndex()">生成内容索引</button>
                    <button class="btn btn-danger" type="button" onclick="genDirectory()" style="float:right; margin-left: 10px;"><i class="icon icon-undo"></i> 更新目录/内容</button>
                    <button class="btn btn-success" type="button" onclick="cleanThumbnail()" style="float:right"><i class="icon icon-eraser"></i> 清理缩略图</button>
                </div>
                <div class="panel-footer">
                    所有配置末尾不要加斜杠，形如 http://www.aa.com/content
                </div>
            </div>
        </div>
        <div role="tabpanel" class="tab-pane fade" id="carousel_tab">
            <div class="panel panel-info">
                <div class="panel-body">
                    <div class="row" id="carousel_group"></div>
                    <div class="row">
                        <button class="btn btn-info" type="button" onclick="addCarousel()">添加项</button>
                        <button class="btn btn-warning" type="button" onclick="deleteCarousel()">删除项</button>
                        <button class="btn btn-primary" type="button" onclick="saveCarousel()">保存设置</button>
                    </div>
                </div>
                <div class="panel-footer">
                    轮播图大小：970 x 410
                </div>
            </div>
        </div>
        <div role="tabpanel" class="tab-pane fade" id="password_tab">
            <div class="panel panel-info">
                <div class="panel-body">
                    <div class="input-group">
                        <span class="input-group-addon">原始密码</span>
                        <input type="password" id="inputRawPassword" class="form-control">
                    </div><br>
                    <div class="input-group">
                        <span class="input-group-addon">新密码</span>
                        <input type="password" id="inputNewPassword" class="form-control">
                    </div><br>
                    <button class="btn btn-primary" type="button" onclick="resetPassword()">重置密码</button>
                </div>
            </div>
        </div>
        <div role="tabpanel" class="tab-pane fade" id="content_tab">
            <div class="panel panel-info">
                <div class="panel-body">
                    <div id="contentDataGrid" class="datagrid" data-ride="datagrid">
                        <div class="input-control search-box search-box-circle has-icon-left has-icon-right" id="searchboxExample2" style="margin-bottom: 10px; max-width: 300px">
                            <input id="inputSearchExample2" type="search" class="form-control search-input" placeholder="搜索名称">
                            <label for="inputSearchExample2" class="input-control-icon-left search-icon"><i class="icon icon-search"></i></label>
                            <a href="#" class="input-control-icon-right search-clear-btn"><i class="icon icon-remove"></i></a>
                        </div>
                        <div class="datagrid-container"></div>
                        <div class="pager"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script th:src="@{/assets/js/jquery.js}"></script>
<script th:src="@{/assets/js/http.js}"></script>
<script th:src="@{/assets/layer/layer.js}"></script>
<script th:src="@{/assets/zui/js/zui.min.js}"></script>
<script th:src="@{/assets/zui/lib/datagrid/zui.datagrid.min.js}"></script>
<script th:inline = "javascript" >
    /*<![CDATA[*/
    var sessionId = [[${session.sessionId}]];
    /*]]>*/
</script>
<script>
    var ws = null, wsUrl = "ws://127.0.0.1:8707/ws/" + sessionId;
    var lockReconnect = false;  //避免ws重复连接

    $(function () {
        // 读取资源信息
        sendJson("get", "/setting/res", null, false, function (res) {
                if (res.code === 0) {
                    $("#inputResContent").val(res.data.resContent);
                    $("#inputResThumbnail").val(res.data.resThumbnail);
                    $("#inputContentIp").val(res.data.contentIp);
                    $("#inputThumbnailIp").val(res.data.thumbnailIp);
                } else {
                    layer.msg(res.message, {icon: 2});
                }
            },
            function () {
                layer.msg("未知错误", {icon: 2});
            });

        // 读取缩略图信息
        sendJson("get", "/setting/carousel", null, false, function (res) {
                if (res.code === 0) {
                    let json = JSON.parse(res.data), html = '';
                    for(let i = 0; i<json.length;i++) {
                        html += '<div class="row mb32">\n' +
                            '<div class="input-control col-md-6">\n' +
                            '  <input type="text" class="form-control" name="carouselLink" value="'+json[i].link+'" placeholder="图片链接">\n' +
                            '</div>\n' +
                            '<div class="input-control col-md-6">\n' +
                            '  <input type="text" class="form-control" name="carouselUrl" value="'+json[i].url+'" placeholder="跳转Url">\n' +
                            '</div>\n' +
                            '</div>';
                    }
                    $("#carousel_group").html(html);
                } else {
                    layer.msg(res.message, {icon: 2});
                }
            },
            function () {
                layer.msg("未知错误", {icon: 2});
            });

        // 检测索引
        sendJson("get", "/es/content/exist", null, false, function (res) {
                if (res.code !== 0) {
                    layer.confirm('检测到内容索引没有初始化，是否立即初始化？', {
                        btn: ['立即建立','以后再说'] //按钮
                    }, function(){
                        sendJson("post", "/es/content/create", null, false, function (res) {
                                if (res.code === 0) {
                                    layer.msg("索引初始化完成，请点击“生成内容索引”按钮建立索引", {icon: 1});
                                } else {
                                    layer.msg(res.message, {icon: 2});
                                }
                            },
                            function () {
                                layer.msg("未知错误", {icon: 2});
                            });
                    }, function(){
                        return false;
                    });
                } else {
                    $("#contentIndexBtn").removeClass("disabled");
                }
            },
            function () {
                layer.msg("未知错误", {icon: 2});
            });

        // 连接WebSocket
        createWebSocket(wsUrl);
    });

    $('#contentDataGrid').datagrid({
        dataSource: {
            cols:[
                {name: 'id', label: 'ID', width: 0.3},
                {name: 'name', label: '名称', width: 0.3},
                {name: 'firstCategoryName', label: '一级目录', width: 109, sort:false},
                {name: 'secondCategoryName', label: '二级目录', width: 109, sort:false},
                {name: 'type', label: '类型'},
                {name: 'click', label: '点击量'},
                {name: 'commentCount', label: '评论数', sort:false},
                {name: 'author', label: '上传用户', width: 109, sort:false},
                {name: 'createDate', label: '上传时间', width: 0.1},
            ],
            remote: function(params) {
                return {
                    url: 'content/list',
                    type: 'GET',
                    dataType: 'json'
                };
            }
        },
        states: {
            pager: {page: 1, recPerPage: 15}
        },
        sortable: true,
        height: 'page'
    });

    // 生成内容索引
    function buildContentIndex() {
        layer.confirm('生成索引将耗费一定时间，是否生成？', {
            btn: ['确定','取消']
        }, function(){
            sendJson("post", "/es/content/build", null, false, function (res) {
                    if (res.code === 0) {
                        layer.msg(res.message, {icon: 1});
                    } else {
                        layer.msg(res.message, {icon: 2});
                    }
                },
                function () {
                    layer.msg("未知错误", {icon: 2});
                });
        }, function(){
        });
    }

    // 更新资源
    function updateRes() {
        let resContent = $("#inputResContent").val();
        let resThumbnail = $("#inputResThumbnail").val();
        let contentIp = $("#inputContentIp").val();
        let thumbnailIp = $("#inputThumbnailIp").val();

        if(resContent == null || resContent == '' ||
            resThumbnail == null || resThumbnail == '' ||
            contentIp == null || contentIp == '' ||
            thumbnailIp == null || thumbnailIp == '') {
            layer.msg("信息不能为空", {icon: 2});
            return false;
        }

        let data = {
            resContent:resContent,
            resThumbnail:resThumbnail,
            contentIp:contentIp,
            thumbnailIp:thumbnailIp
        };

        sendJson("post", "/setting/res", data, false, function (res) {
                if (res.code === 0) {
                    layer.msg("更新成功", {icon: 1});
                } else {
                    layer.msg(res.message, {icon: 2});
                }
            },
            function () {
                layer.msg("未知错误", {icon: 2});
            });
    }

    // 清理缩略图 WebSocket
    function cleanThumbnail() {
        layer.confirm("清理缩略图将耗费一定时间，确定清理？", {
            btn: ['确定', '取消']
        }, function () {
            sendJson("delete", "thumbnail/clean", null, false, function (res) {
                if (res.code !== 0) {
                    layer.msg(res.message, {icon: 2});
                } else {
                    layer.msg(res.message, {icon: 1});
                }
            }, function () {
                layer.msg("未知错误", {icon: 2});
            });
        }, function () {
        });
    }

    // 生成目录 WebSocket
    function genDirectory() {
        layer.confirm("重新生成耗时较长确定要重新生成目录吗？", {
            btn: ['确定', '取消']
        }, function () {
            sendJson("post", "/category/gen", null, false, function (res) {
                if (res.code !== 0) {
                    layer.msg(res.message, {icon: 2});
                } else {
                    layer.msg(res.message, {icon: 1});
                }
            }, function () {
                layer.msg("未知错误", {icon: 2});
            });
        }, function () {
        });
    }

    // 重置密码
    function resetPassword() {
        let rawPassword = $("#inputRawPassword").val();
        let newPassword = $("#inputNewPassword").val();

        if(rawPassword == null || rawPassword == '' ||
            newPassword == null || newPassword == '') {
            layer.msg("原始密码或新密码", {icon: 2});
            return false;
        }

        let data = {
            rawPassword:rawPassword,
            newPassword:newPassword
        };

        sendJson("post", "/user/password", data, false, function (res) {
                if (res.code === 0) {
                    layer.msg("修改成功，即将退出登录", {icon: 1});
                    setTimeout(function () {
                        window.location.href='/logout';
                    }, 2000);

                } else {
                    layer.msg(res.message, {icon: 2});
                }
            },
            function () {
                layer.msg("未知错误", {icon: 2});
            });
    }

    function addCarousel() {
        let html = '<div class="row mb32">\n' +
            '<div class="input-control col-md-6">\n' +
            '  <input type="text" class="form-control" name="carouselLink" placeholder="图片链接">\n' +
            '</div>\n' +
            '<div class="input-control col-md-6">\n' +
            '  <input type="text" class="form-control" name="carouselUrl" placeholder="跳转Url">\n' +
            '</div>\n' +
            '</div>';
        $("#carousel_group").append(html);
    }

    function deleteCarousel() {
        $("#carousel_group").children().last().remove();
    }
    
    function saveCarousel() {
        let links = $("input[name='carouselLink']");
        let urls = $("input[name='carouselUrl']");
        let array = new Array();

        for(let i =0; i<links.length; i++) {
            let link = $(links[i]).val();
            let url = $(urls[i]).val();

            if(link != null && link !== '') {
                array.push({link:link,url:url});
            }
        }

        if(array.length > 0) {
            sendJson("post", "/setting/carousel", {json:JSON.stringify(array)}, false, function (res) {
                if (res.code !== 0) {
                    layer.msg(res.message, {icon: 2});
                } else {
                    layer.msg("保存成功", {icon: 1});
                }
            }, function () {
                layer.msg("未知错误", {icon: 2});
            });
        }
    }

    <!-- WebSocket 相关 -->
    // 建立连接
    function createWebSocket(url) {
        if ('WebSocket' in window) {
            ws = new WebSocket(url);
        } else if ('MozWebSocket' in window) {
            ws = new MozWebSocket(url);
        } else {
            layer.msg('您的浏览器不支持WebSocket，请更换浏览器', {icon: 2});
        }
        initEventHandle();
    }

    // 初始化相关回调函数
    function initEventHandle() {
        //连接成功建立的回调方法
        ws.onopen = function(){
            console.log("WebSocket connect.");
            //心跳检测重置
            heartCheck.reset().start();
        };

        //接收到消息的回调方法
        ws.onmessage = function(event){
            //拿到任何消息都说明当前连接是正常的，重置心跳
            heartCheck.reset().start();

            // 处理服务端消息
            if(event.data !== "pong") {
                new $.zui.Messager(event.data, {type: 'info', time:6000}).show();
            } else {
                console.log("WebSocket rec: pong");
            }
        };

        //连接关闭的回调方法
        ws.onclose = function(){
            console.log("WebSocket close.");
            // 重连WebSocket
            reconnect(wsUrl);
        };

        //连接发生错误的回调方法
        ws.onerror = function(){
            console.log("WebSocket error.");
            // 重连WebSocket
            reconnect(wsUrl);
        };
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭webSocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        ws.close();
    };

    // 重连WebSocket
    function reconnect(url) {
        if (lockReconnect)
            return;
        lockReconnect = true;

        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }


    //心跳检测
    var heartCheck = {
        timeout: 10000,        // 10s发一次心跳
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () { //心跳包重置
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                // 向后台发送心跳
                ws.send("ping");
                self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置，说明后端主动断开了
                    // 执行ws.close()会回调onclose，然后执行其中的reconnet。如果直接执行reconnect 会触发onclose导致重连两次
                    ws.close();
                }, self.timeout)
            }, this.timeout)
        }
    };

    //关闭连接
    function closeWebSocket(){
        ws.close();
    }
</script>
</body>
</html>